package winsvc

import (
	"fmt"

	"golang.org/x/sys/windows/svc/mgr"
)

// GetServiceStatus 获取服务当前状态
func (s *serviceImpl) GetServiceStatus() (State, error) {
	m, err := mgr.Connect()
	if err != nil {
		return 0, fmt.Errorf("无法连接到服务管理器: %v", err)
	}
	defer m.Disconnect()

	service, err := m.OpenService(s.config.ServiceName)
	if err != nil {
		return 0, fmt.Errorf("服务 %s 不存在: %v", s.config.ServiceName, err)
	}
	defer service.Close()

	status, err := service.Query()
	if err != nil {
		return 0, fmt.Errorf("无法查询服务状态: %v", err)
	}
	return State(status.State), nil
}

// IsServiceExist 检查服务是否存在
func (s *serviceImpl) IsServiceExist() bool {
	m, err := mgr.Connect()
	if err != nil {
		return false
	}
	defer m.Disconnect()

	service, err := m.OpenService(s.config.ServiceName)
	if err != nil {
		return false
	}
	defer service.Close()
	return true
}

// Install 安装服务
func (s *serviceImpl) Install() {
	s.handleServiceCommand(methodInstall)
}

// Uninstall 卸载服务
func (s *serviceImpl) Uninstall() {
	s.handleServiceCommand(methodUninstall)
}

// Start 启动服务
func (s *serviceImpl) Start() {
	s.handleServiceCommand(methodStart)
}

// Stop 停止服务
func (s *serviceImpl) Stop() {
	s.handleServiceCommand(methodStop)
}

// Restart 重启服务
func (s *serviceImpl) Restart() {
	s.handleServiceCommand(methodRestart)
}
